/**
 * @project lauwsys
 */
package com.chimoz.lauwsys.repository.jpa;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.chimoz.lauwsys.domain.Brand;
import com.chimoz.lauwsys.repository.BrandRepository;

/**
 * @author Christian Teguh
 * @created 13 Okt 2011 16.36.09
 */
@Repository
public class PBrandRepository implements BrandRepository {

	@Value("${jpa.sql.brand.insert}")
	private String insertBrandQuery;
	
	@Value("${jpa.sql.brand.update}")
	private String updateBrandQuery;
	
	@Value("${jpa.sql.brand.remove}")
	private String removeBrandQuery;
	
	@Value("${jpa.sql.brand.queryById}")
	private String brandByIdQuery;
	
	@Value("${jpa.sql.brand.queryAll}")
	private String allBrandQuery;
	
	
	@PersistenceContext
	private EntityManager entityManager;
	
	private CriteriaQuery<Brand> criteriaBrand() {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		return cb.createQuery(Brand.class);
	}
	
	public Brand saveBrand(Brand brand) {
		if ( brand.getId() != null ) {
			Brand newBrand = entityManager.find( Brand.class, brand.getId() );
			newBrand.setName( brand.getName() );
			newBrand.setDesc( brand.getDesc() );
			newBrand.setCtime( brand.getCtime() );
			newBrand.setMtime( (int) (System.currentTimeMillis() / 1000L) );
		} else {
			entityManager.persist(brand);
			entityManager.flush();
		}	
		return brand;
	}
	
	public void removeBrand(Brand brand) {
		entityManager.remove(brand);
	}

	public Brand getBrandById(Long id) {
		return entityManager.find(Brand.class, id);
	}

	// When using JPQL you must use the class attribute name. Use native sql
	public List<Brand> listBrand(Map<String, String> criteria) {
		
		Integer offset = new Integer( criteria.get("offset") );
		Integer limit = new Integer( criteria.get("limit") );
		
		Query query = entityManager.createQuery(criteriaBrand())
								.setFirstResult(offset)
								.setMaxResults(limit);
		
		return query.getResultList();
	}

}
